package com.chexiehui.jc.ui.activity;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.AuthInfo;
import com.chexiehui.jc.entity.UserInfo;
import com.chexiehui.jc.event.ReceiveRegistrationIdEvent;
import com.chexiehui.jc.mvp.login.FindPasswordCovenant;
import com.chexiehui.jc.mvp.login.FindPasswordPresenter;
import com.chexiehui.jc.utils.CodeCountDownTimer;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.SerializableSpTools;

import org.greenrobot.eventbus.Subscribe;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * 找回密码
 */
public class FindPasswordActivity extends BaseMvpActivity<FindPasswordPresenter> implements FindPasswordCovenant.View {

    @BindView(R.id.tv_page_tip)
    TextView tvPageTip;
    @BindView(R.id.tv_page_title)
    TextView tvPageTitle;
    @BindView(R.id.rl_head_container)
    RelativeLayout rlHeadContainer;
    @BindView(R.id.tv_phone_pre)
    TextView tvPhonePre;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.tv_code_pre)
    TextView tvCodePre;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.rtv_next)
    RadiusTextView rtvNext;
    @BindView(R.id.ll_phone_input_panel)
    LinearLayout llPhoneInputPanel;
    @BindView(R.id.et_password_first)
    EditText etPasswordFirst;
    @BindView(R.id.et_password_second)
    EditText etPasswordSecond;
    @BindView(R.id.rtv_submit)
    RadiusTextView rtvSubmit;
    @BindView(R.id.ll_password_input_panel)
    LinearLayout llPasswordInputPanel;
    // 0 获取验证码 1 输入密码
    private int pageType = 0;
    private CodeCountDownTimer phoneLoginTimer;
    private String registrationId = "";

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Subscribe
    public void onReceiveRegistrationIdEvent(ReceiveRegistrationIdEvent event){
        if(event != null && !StringUtils.isTrimEmpty(event.getRegistrationId())){
            registrationId = event.getRegistrationId();
        }
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("")
                .setBgColor(ContextCompat.getColor(mContext, R.color.colorTransparent))
                .setOnLeftTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        if (pageType == 1) {
                            changePageType(0);
                        } else {
                            onBackPressed();
                        }
                    }
                });
    }

    private void changePageType(int type) {
        pageType = type;
        if (pageType == 0) {
            tvPageTip.setText("请输入绑定的手机号");
            tvPageTitle.setText("找回密码");
            llPhoneInputPanel.setVisibility(View.VISIBLE);
            llPasswordInputPanel.setVisibility(View.GONE);
        } else {
            tvPageTip.setText("请输入新密码");
            tvPageTitle.setText("设置密码");
            llPhoneInputPanel.setVisibility(View.GONE);
            llPasswordInputPanel.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_find_password;
    }

    @Override
    protected void initView(Bundle var1) {
        registrationId = JPushInterface.getRegistrationID(mContext);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) rlHeadContainer.getLayoutParams();
        lp.width = ScreenUtils.getScreenWidth();
        lp.height = BigDecimal.valueOf(lp.width).multiply(BigDecimal.valueOf(201))
                .divide(BigDecimal.valueOf(375), 2, BigDecimal.ROUND_HALF_UP).intValue();
        rlHeadContainer.setLayoutParams(lp);
        changePageType(0);
        rtvNext.setEnabled(false);
    }

    @OnClick({R.id.tv_get_code, R.id.rtv_next, R.id.rtv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_code:
                mvpPresenter.getCode(etPhone.getText().toString());
                break;
            case R.id.rtv_next:
                if (StringUtils.isTrimEmpty(etPhone.getText().toString())) {
                    showToast("请输入手机号");
                    return;
                }
                if (!RegexUtils.isMobileSimple(etPhone.getText().toString())) {
                    showToast("请输入正确的手机号码");
                    return;
                }
                if (StringUtils.isTrimEmpty(etCode.getText().toString())) {
                    showToast("请输验证码");
                    return;
                }
                if (etCode.getText().toString().trim().length() != 6) {
                    showToast("请输入6位验证码");
                    return;
                }
                mvpPresenter.getCheckCode(etPhone.getText().toString().trim(),etCode.getText().toString());
                break;
            case R.id.rtv_submit:
                mvpPresenter.submit(etPhone.getText().toString(), etCode.getText().toString(),
                        etPasswordFirst.getText().toString(), etPasswordSecond.getText().toString());
                break;
        }
    }

    @Override
    protected FindPasswordPresenter createPresenter() {
        return new FindPasswordPresenter(this);
    }

    @Override
    public void onGetCodeSuccess(BaseModel<Object> successResult) {
        showToast(String.format(getStringSource(R.string.s_yzmyfs_tips_),
                etPhone.getText().toString().trim()));
        if (phoneLoginTimer == null) {
            phoneLoginTimer = new CodeCountDownTimer(tvGetCode, 60000, 1000);
        }
        phoneLoginTimer.start();
        rtvNext.setEnabled(true);
    }

    @Override
    public void onGetCodeFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onCheckCodeSuccess(BaseModel<Object> successResult) {
        hide();
        showToast("验证成功");
        changePageType(1);

    }

    @Override
    public void onCheckCodeFailure(BaseModel<Object> failureResult) {
        showToast("验证码错误");

    }

    @Override
    public void onSubmitSuccess(BaseModel<AuthInfo> successResult) {
        SerializableSpTools.putAuthInfo(successResult.getData());
        mvpPresenter.getUserInfo();
    }

    @Override
    public void onSubmitFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onGetUserInfoSuccess(BaseModel<UserInfo> successResult) {
        SerializableSpTools.putUserInfo(successResult.getData());
        SerializableSpTools.setIsLogin(true);
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onGetUserInfoFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
        SerializableSpTools.clearAuthInfo();
        SerializableSpTools.clearUserInfo();
    }

    @Override
    public String getIm() {
        return registrationId;
    }

    @Override
    public void onBackPressed() {
        if (pageType == 1) {
            changePageType(0);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        if (phoneLoginTimer != null) {
            phoneLoginTimer.release();
            phoneLoginTimer = null;
        }
        super.onDestroy();
    }
}
